<!-- src/components/Message.vue -->
<template>
  <teleport to="body">
    <transition-group name="message-list">
      <div 
        v-for="message in messages" 
        :key="message.id"
        class="message-item"
        :class="message.type"
      >
        {{ message.content }}
      </div>
    </transition-group>
  </teleport>
</template>

<script setup>
import { ref } from 'vue'

const messages = ref([])
let id = 0

const addMessage = (content, type = 'info', duration = 3000) => {
  const messageId = id++
  messages.value.push({ id: messageId, content, type })
  
  if (duration > 0) {
    setTimeout(() => {
      removeMessage(messageId)
    }, duration)
  }
}

const removeMessage = (id) => {
  messages.value = messages.value.filter(msg => msg.id !== id)
}

// 暴露方法供外部调用
defineExpose({ addMessage, removeMessage })
</script>

<style scoped>
.message-item {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  border-radius: 4px;
  color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 9999;
  margin-bottom: 10px;
  pointer-events: none;
}

.message-item.info {
  background-color: #909399;
}

.message-item.success {
  background-color: #67c23a;
}

.message-item.warning {
  background-color: #e6a23c;
}

.message-item.error {
  background-color: #f56c6c;
}

.message-list-enter-active,
.message-list-leave-active {
  transition: all 0.3s ease;
}

.message-list-enter-from,
.message-list-leave-to {
  opacity: 0;
  transform: translate(-50%, -20px);
}

.message-list-leave-active {
  position: absolute;
}
</style>